/**
 * This file is part of Sonedyan.
 * 
 * Sonedyan is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * either version 3 of the License, or (at your option) any
 * later version.
 *
 * Sonedyan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public
 * License along with Octave; see the file COPYING.  If not
 * see <http://www.gnu.org/licenses/>.
 * 
 * Copyright (C) 2009-2012 Jimmy Dubuisson <jimmy.dubuisson@gmail.com>
 */

package org.unige.mpej.eckmann.sonedyan.enron.db.autoincrement;

import org.unige.mpej.eckmann.sonedyan.enron.db.Db4oHandler;

/**
 * auto increment id template
 * 
 * this class has to be extended for creating a new primary key (e.g. EmailId)
 */
public class IncrementedId
{
	private int id;
	private static IncrementedId instance;
	
	/**
	 * private constructor
	 */
	private IncrementedId()
	{
		this.id = 0;
	}
	
	/**
	 * 
	 * @param db
	 * @return
	 */
	public int getNextID(Db4oHandler db)
	{
		this.id++;
		db.store(this);
		return this.id;
	}
	
	/**
	 * 
	 * @param db
	 * @return an incremented id instance
	 */
	public static IncrementedId getIdObject(Db4oHandler db)
	{
		// if instance is not assigned yet:
		if (instance == null) 
		{
			// check if there is a stored instance from the previous 
			// session in the database
			instance = AutoIncrementUtils.getIncrementedId(db);
		}
	
		// if no autoincrement id was found in the database
		// create a new instance
		if (instance == null) 
		{
			// create new instance and store it
			instance = new IncrementedId();
			db.store(instance);
		}
		
		return instance;
	}
	
}
